package create.obj;

import java.io.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Test  implements Cloneable, Serializable {


    public Test(){

    }
    public int a = 80;

    public TestSub testSub = new TestSub();

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, CloneNotSupportedException, IOException, InvocationTargetException {


        //1、new

        //2、反射
//        Class<?> aClass = Class.forName("create.obj.Test");
//        Test o = (Test)aClass.newInstance();
//        System.out.println(o.a);





        //3、clone 克隆   深克隆 浅克隆
        Test test1 = new Test();
        Test test = (Test)test1.clone();
        System.out.println(test.a);
        //浅克隆 克隆出来的对象内部的成员变量内存地址相等
        System.out.println(test.testSub);
        System.out.println(test1.testSub);
        System.out.println(test1.testSub==test.testSub);
        //深克隆 克隆出来的对象内部的成员变量内存地址不相等


        //4 通过序列化
//        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("D://a.txt"));
//        Test test = new Test();
//        objectOutputStream.writeObject(test);
//        objectOutputStream.flush();
//        objectOutputStream.close();
//
//        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("D://a.txt"));
//        Test object = (Test)objectInputStream.readObject();
//        System.out.println(object.a);
//        objectInputStream.close();

        // 5 反射构造器
//        Class<?> aClass = Class.forName("create.obj.Test");
//        Constructor<?>[] constructors = aClass.getConstructors();
//        Test o = (Test)constructors[0].newInstance();
//        System.out.println(o.a);


    }

    @Override
    public Test clone() throws CloneNotSupportedException {
        Test test =  ((Test) super.clone());
        test.testSub = test.testSub.clone();
        return test;
    }
}

class TestSub implements Cloneable,Serializable{
    private int a = 0;
    private int b = 0;


    @Override
    protected TestSub clone() throws CloneNotSupportedException {
        return (TestSub) super.clone();
    }
}
